package cn.itcast.star.graph.core.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import cn.itcast.star.graph.core.dto.UserLoginRequestDTO;
import cn.itcast.star.graph.core.dto.UserLoginResponseDTO;
import cn.itcast.star.graph.core.mapper.UserMapper;
import cn.itcast.star.graph.core.pojo.User;
import cn.itcast.star.graph.core.service.UserService;
import cn.itcast.star.graph.core.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 登录请求
     * @return
     */
    @Override
    public UserLoginResponseDTO login(UserLoginRequestDTO dto) {
        //1.判断参数,校验非空
        if (StringUtil.isBlank(dto.getUsername()) || StringUtil.isBlank(dto.getPassword())) {
            throw new RuntimeException("用户名或密码不能为空!");
        }

        //2.查数据库,判断是否有用户
        LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>lambdaQuery().eq(User::getUsername, dto.getUsername())
                .or()
                .eq(User::getMobile, dto.getPassword());

        User user = baseMapper.selectOne(queryWrapper);

        if (user == null) {
            throw new RuntimeException("用户名或密码不正确!");
        }

        //3.判断密码是否正确(密码为md5+盐加密)
        //3.1输入的密码按加密规则加密
        //3.2对比密码
        if(!BCrypt.checkpw(dto.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码不正确!");
        }

        //4.返回token
        UserLoginResponseDTO userLoginResponseDTO = new UserLoginResponseDTO();
        userLoginResponseDTO.setId(user.getId());
        userLoginResponseDTO.setName(user.getUsername());
        userLoginResponseDTO.setAvatar(user.getAvatar());
        userLoginResponseDTO.setToken(JwtUtil.genToken(user));

        return userLoginResponseDTO;
    }
}
